<?php
namespace App\Logics;

use App\Models\OrderGroupBinModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\OrderGroupModel;

//逻辑处理
class OrderGroupLogic extends BaseLogic {
    public function __construct( )
    {
        parent::__construct();
    }

    public static function getList(array $where=[],array $fields=['*']){

        $data= OrderGroupModel::where($where)->select($fields)->get();
        return ob_to_array($data);
    }

    /** 订单分组列表
     * @param array $para
     * @return array
     */
    public  function getOrderGroupList(array $para){
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $id= isset($para['id'])?$para['id']:0;
        $name =isset($para['name'])?$para['name']:'';
        $where = $searchWhere = [];
        if($id>0){
            $where['id']=$id;
            $searchWhere[]=['id',$id];
        }
        if($name){
            $where['name']=$name;
            $searchWhere[]=['name','like',$name.'%'];
        }

        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }

        $model = OrderGroupModel::where($searchWhere);
        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);
        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?';
        foreach ($where as $k => $v) {
            $url .= "&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        $arr=[
            'data'=>$data,
            'where'=>$where,
        ];

        return $arr;
    }

    /** 编辑分组
     * @param array $para
     * @return array
     */
    public   function edit(array $para){
        $id= isset($para['id'])?$para['id']:0;
        $name=isset($para['name'])?$para['name']:'';
        $desc=isset($para['desc'])?$para['desc']:'';

        if($id<1)  return error('参数有误');
        if(!$name)  return error('分组名不能为空');
        $num=OrderGroupLogic::checkNameUnique($name,$id);
        if($num>0)  return error('该分组名已经存在');

        $res= OrderGroupModel::where('id',$id)->update(['name'=>$name,'desc'=>$desc]);
        if(!$res) return error('编辑失败');
        return success('ok');
    }

    /** 添加分组
     * @param array $para
     * @return array
     */
    public   function add(array $para){
        $id= isset($para['id'])?$para['id']:0;
        $name=isset($para['name'])?$para['name']:'';
        $desc=isset($para['desc'])?$para['desc']:'';
        if(!$name)  return error('分组名不能为空');
        $num=OrderGroupLogic::isOneByName($name);
        if($num>0) return error('该分组名已经存在');
        $res= OrderGroupModel::insert(['name'=>$name,'desc'=>$desc]);
        if(!$res) return error('添加失败');
        return success('添加成功');
    }


    //获取一个
    public static function  getOne($id,$fields=['*']){
        $id=(int)$id;
        $data= OrderGroupModel::where('id',$id)->select($fields)->first();
        return ob_to_array($data);
    }


    //判断该数据是否存在
    public static function isOne($id){
        $id=(int)$id;

        return OrderGroupModel::where('id',$id)->count();
    }

    //判断该数据是否存在
    public static function isOneByName($name){
        $name=trim($name);

        return OrderGroupModel::where('name',$name)->count();
    }

    //检测分组名称
    public static function checkNameUnique($name,$id=0){
        $name=trim($name);
        $where=[['name',$name]];
        if($id>0) $where[]=['id','<>',$id];
        return OrderGroupModel::where($where)->count();
    }

    public static function pluck(string $name,$key=null,array $where=[]){
        return OrderGroupModel::where($where)->pluck($name,$key)->toArray();
    }

    //删除分组及分组设置
    public   function delete($id){
        DB::beginTransaction();
        try{
            $res= OrderGroupModel::where('id',$id)->delete();
            if(empty($res)) throw new \Exception('删除失败');
            $n= OrderGroupBinModel::where('group_id',$id)->count();
            if($n>0){
                $res= OrderGroupBinModel::where('group_id',$id)->delete();
                if(empty($res)) throw new \Exception('删除失败');
            }
            DB::commit();
            return success('删除成功');
        }catch (\Exception $e){
            DB::rollBack();
            return error($e->getMessage());

        }
        return success('删除成功');
    }

    /** 订单分组列表
     * @param array $para
     * @return array
     */
    public   function groupOrderList(array $para){
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $order_status=isset($para['order_status'])?$para['order_status']:-1;
        $order_type=isset($para['order_type'])?$para['order_type']:0;
        $order_comefrom =isset($para['order_comefrom'])?$para['order_comefrom']:'';
        $order_id=isset($para['order_id'])?$para['order_id']:'';
        $goods_name=isset($para['goods_name'])?$para['goods_name']:'';
        $user_phone=isset($para['user_phone'])?$para['user_phone']:'';
        $user_name=isset($para['user_name'])?$para['user_name']:'';
        $start_time=isset($para['start_time'])?$para['start_time']:'';
        $end_time=isset($para['end_time'])?$para['end_time']:'';
        $group_id = isset($para['group_id'])?$para['group_id']:0;

        $where = $searchWhere = [];
        $whereRaw='';$whereCol=[];

        if($order_status!=-1 ){
            $where['order_status'] = $order_status;
            $searchWhere[] = ['order_status',$order_status];
        }


        if($order_type){
            $where['order_type'] = $order_type;
            $searchWhere[] = ['order_type',$order_type];
        }
        if($order_comefrom){
            $where['order_comefrom'] = $order_comefrom;
            $searchWhere[] = ['order_comefrom',$order_comefrom];
        }

        if ($order_id) {
            $where['order_id'] = $order_id;
            $searchWhere[] = ['order_id', 'like', $order_id . '%'];
        }
        if ($goods_name) {
            $where['goods_name'] = $goods_name;
            $searchWhere[] = ['goods_name', 'like', $goods_name . '%'];
        }
        if ($user_phone) {
            $where['user_phone'] = $user_phone;
            $searchWhere[] = ['user_phone', 'like', $user_phone . '%'];
        }
        if ($user_name) {
            $where['user_name'] = $user_name;
            $searchWhere[] = ['user_name', 'like', $user_name . '%'];
        }
        if ($start_time) {
            $where['start_time'] = $start_time;
            $whereRaw.="`order_create_time` > ? ";
            $whereCol[]=$start_time;
        }
        if ($end_time) {
            $where['end_time'] = $end_time;
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.="`order_create_time` <  ? ";
            $whereCol[]=$end_time;
        }
        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }
        if($group_id>0){
            $where['group_id']=$group_id;
            $order_ids=OrderLogic::getOrderIdsByGroupId($group_id)?:[0];
        }

        $model =  OrderModel::where($searchWhere);
        if($group_id>0 && $order_ids) $model->whereIn('order_id',$order_ids);


        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);
        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);
        $order_ids=$data['data']?array_column($data['data'],'order_id'):[0];
        $xxhf=LogXxhfLogic::getResByOrderIds($order_ids);
        $channel=ChannelLogic::pluck('cha_describe','cha_name');
        $url=config('sys.img_url').'/';
        $order_status=config('sys.order_status');
        $groups=OrderLogic::getGroupNameByOrderIds($order_ids);
        foreach($data['data'] as $k=>$v){
            $data['data'][$k]["goods_order_thumbnail"]=$url.trim($v['goods_order_thumbnail'],'/');
            $data['data'][$k]["order_address"]=$v["user_province"].$v["user_address"];
            $data['data'][$k]["order_comefrom"]=$channel[$v['order_comefrom']]??'';//订单来源
            $data['data'][$k]['log_xxhf']=$xxhf[$v['order_id']]??'';
            $data['data'][$k]['order_status']=$order_status[$v['order_status']]??'';
            $data['data'][$k]['group_name']=$groups[$v['order_id']]??[];
        }


        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        $excel_url='?';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
            $excel_url.="&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        if(isset($where['per_page']))unset($where['per_page']);

        $order_group=OrderGroupLogic::pluck('name','id');
        $arr=[
            'data'=>$data,
            'where'=>$where,
            'url'=>$url,
            'channel'=>$channel,
            'excel_url'=>$excel_url,
            'order_group'=>$order_group
        ];
        return $arr;
    }







}
